# onlyoffice/index.vue文件内容
<template>
  <div style="overflow: scroll;height: calc(100vh - 84px);">
    <div :id="onlineEditorId"></div>
  </div>
</template>
<script>
import {getOnlyOfficeConfig} from "@/api/documents";

export default {
  name: "OnlineEditor",
  data() {
    return {
      // 文档ID
      documentId: '',
      // 文档版本号
      versionId: '',
      // 打开文件的方式，true-编辑模式，false-预览模式
      isEdit: true,
      docEditor: null,
      onlineEditorId: 'onlineEditor',
    }
  },
  watch: {
    documentId: {
      handler: function () {
        this.loadScript();
        this.initEditor();
      },
      deep: true,
    },
  },
  activated() {
    if (this.documentId) {
      this.loadScript();
      this.initEditor();
    }
  },
  created() {
    // 从路由中获取参数
    const documentId =1;
    const versionId = this.$route.query.versionId;
    const isEdit = this.$route.query.isEdit;
    if (versionId) this.versionId = versionId;
    if (isEdit) this.isEdit = isEdit;
    if (documentId) {
      this.documentId = documentId;
      this.onlineEditorId += this.documentId;
      this.loadScript();
      this.initEditor();
    }
  },
  methods: {
    // 动态加载onlyoffice api脚本
    async loadScript(){
      const scriptId = "script_"+this.documentId;
      if (document.getElementById(scriptId)===null){
        const script = document.createElement('script')
        script.id = scriptId;
        script.src = "http://36.137.225.215:7799/onlyoffice/web-apps/apps/api/documents/api.js"
        script.type = "text/javascript"
        document.head.appendChild(script);
      }
    },
    // 初始化onlyoffice编辑器
    async initEditor(){
      const scriptId = "script_"+this.documentId;
      if (document.getElementById(scriptId)===null){
        await this.loadScript();
      }
      // 保证每次刷新页面时重新加载onlyoffice对象，避免缓存问题
      if (this.docEditor){
        this.docEditor.destroyEditor();
        this.docEditor = null;
      }
      const param = {
        documentId: this.documentId,
        versionId: this.versionId,
        isEdit: this.isEdit
      }
      // 从后端获取onlyoffice配置，避免配置被修改
      await getOnlyOfficeConfig(param).then(res=>{
        let data = res.data;
        console.log('data=>',data);
        this.docEditor = new window.DocsAPI.DocEditor(this.onlineEditorId, data);
      })
    },
  },
  // 关闭页面销毁onlyoffice对象
  beforeDestroy() {
    if (this.docEditor){
      this.docEditor.destroyEditor();
      this.docEditor = null;
    }
  }
}
</script>
<style scoped lang="scss">

</style>

